package com.sodaopen.study.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sodaopen.study.entity.AjaxResult;
import com.sodaopen.study.entity.User;
import com.sodaopen.study.service.UserService;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @GetMapping("/login")
    public String login(){
        return "login";
    }
    
    @ResponseBody
	@RequestMapping("/doAjaxLogin")
	public Object doAjaxLogin(String username, String password, HttpSession session) {
		User user = userService.findUserByUsername(username);
		
		AjaxResult result = new AjaxResult();
		if(user != null && user.getPassword().equals(password)) {
			session.setAttribute("loginUser", user);
			result.setSuccess(true);
		}else {
			result.setSuccess(false);
			result.setData("用户名或密码错误！");
		}
		
		return result;
    }
    
    @GetMapping("/logout")
    public String logout(HttpSession session){
    	session.invalidate();
        return "redirect:login";
    }
    
    
    @GetMapping("/register")
    public String register(){
        return "register";
    }
		
    
    @RequestMapping("/ajaxCheckUsername")
	@ResponseBody
	public Object ajaxCheckUsername(String username) {
		User user = userService.findUserByUsername(username);
		return user == null;
	}
    
    @ResponseBody
	@RequestMapping("/doAjaxRegister")
	public Object doAjaxRegister(User user, HttpSession session) {
		
		AjaxResult result = new AjaxResult();
		try {
			userService.registerUser(user);
			result.setSuccess(true);
		}catch (Exception e) {
			result.setData("注册失败");
		}
		
		return result;
    }

}
